'use client';

import React, { useState, useEffect } from 'react';
import {
  Table,
  Button,
  Input,
  Select,
  Space,
  Tag,
  Modal,
  Form,
  message,
  Popconfirm,
  Tooltip,
  Card,
  Row,
  Col,
  Statistic,
  Badge,
  Switch,
  Divider,
  Tree
} from 'antd';
import {
  KeyOutlined,
  EditOutlined,
  DeleteOutlined,
  PlusOutlined,
  SearchOutlined,
  ReloadOutlined,
  EyeOutlined,
  SafetyOutlined,
  FolderOutlined,
  FileOutlined,
  SettingOutlined,
  ApiOutlined,
  DatabaseOutlined,
  GlobalOutlined
} from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';
import type { DataNode } from 'antd/es/tree';
import AdminLayout from '../AdminLayout';
import styles from './Permissions.module.scss';

const { Search } = Input;
const { Option } = Select;
const { TextArea } = Input;

interface Permission {
  id: string;
  name: string;
  display_name: string;
  description?: string;
  category: string;
  resource_type: string;
  resource_id?: string;
  action: string;
  is_system: boolean;
  is_active: boolean;
  created_at: string;
  updated_at: string;
  role_count?: number;
  user_count?: number;
}

interface PermissionListResponse {
  success: boolean;
  data: Permission[];
  total: number;
  page: number;
  limit: number;
  stats?: {
    total: number;
    active: number;
    system: number;
    custom: number;
    categories: Record<string, number>;
  };
}

interface CreatePermissionData {
  name: string;
  display_name: string;
  description?: string;
  category: string;
  resource_type: string;
  resource_id?: string;
  action: string;
  is_active: boolean;
}

const PermissionsPage: React.FC = () => {
  const [permissions, setPermissions] = useState<Permission[]>([]);
  const [loading, setLoading] = useState(false);
  const [total, setTotal] = useState(0);
  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize, setPageSize] = useState(20);
  const [searchText, setSearchText] = useState('');
  const [categoryFilter, setCategoryFilter] = useState<string>('');
  const [resourceTypeFilter, setResourceTypeFilter] = useState<string>('');
  const [isSystemFilter, setIsSystemFilter] = useState<string>('');
  const [isActiveFilter, setIsActiveFilter] = useState<string>('');
  const [stats, setStats] = useState<any>(null);
  const [createModalVisible, setCreateModalVisible] = useState(false);
  const [editModalVisible, setEditModalVisible] = useState(false);
  const [treeModalVisible, setTreeModalVisible] = useState(false);
  const [selectedPermission, setSelectedPermission] = useState<Permission | null>(null);
  const [createForm] = Form.useForm();
  const [editForm] = Form.useForm();

  // 权限分类选项
  const categoryOptions = [
    { label: '用户管理', value: 'user_management' },
    { label: '内容管理', value: 'content_management' },
    { label: '系统设置', value: 'system_settings' },
    { label: 'AI功能', value: 'ai_features' },
    { label: '数据分析', value: 'data_analytics' },
    { label: '其他', value: 'other' }
  ];

  // 资源类型选项
  const resourceTypeOptions = [
    { label: 'API接口', value: 'api' },
    { label: '页面路由', value: 'route' },
    { label: '数据库表', value: 'table' },
    { label: '文件系统', value: 'file' },
    { label: '系统功能', value: 'feature' },
    { label: '其他', value: 'other' }
  ];

  // 操作类型选项
  const actionOptions = [
    { label: '查看', value: 'read' },
    { label: '创建', value: 'create' },
    { label: '编辑', value: 'update' },
    { label: '删除', value: 'delete' },
    { label: '执行', value: 'execute' },
    { label: '管理', value: 'manage' }
  ];

  // 获取权限列表
  const fetchPermissions = async () => {
    setLoading(true);
    try {
      const params = new URLSearchParams({
        page: currentPage.toString(),
        limit: pageSize.toString(),
        ...(searchText && { search: searchText }),
        ...(categoryFilter && { category: categoryFilter }),
        ...(resourceTypeFilter && { resource_type: resourceTypeFilter }),
        ...(isSystemFilter && { is_system: isSystemFilter }),
        ...(isActiveFilter && { is_active: isActiveFilter })
      });

      const response = await fetch(`/api/admin/permissions?${params}`);
      const result: PermissionListResponse = await response.json();

      if (result.success) {
        setPermissions(result.data);
        setTotal(result.total);
        setStats(result.stats);
      } else {
        message.error('获取权限列表失败');
      }
    } catch (error) {
      message.error('网络错误');
    } finally {
      setLoading(false);
    }
  };

  // 创建权限
  const handleCreatePermission = async (values: CreatePermissionData) => {
    try {
      const response = await fetch('/api/admin/permissions', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(values),
      });

      const result = await response.json();
      if (result.success) {
        message.success('权限创建成功');
        setCreateModalVisible(false);
        createForm.resetFields();
        fetchPermissions();
      } else {
        message.error(result.error || '创建权限失败');
      }
    } catch (error) {
      message.error('网络错误');
    }
  };

  // 更新权限
  const handleUpdatePermission = async (values: Partial<Permission>) => {
    if (!selectedPermission) return;

    try {
      const response = await fetch(`/api/admin/permissions/${selectedPermission.id}`, {
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(values),
      });

      const result = await response.json();
      if (result.success) {
        message.success('权限更新成功');
        setEditModalVisible(false);
        editForm.resetFields();
        setSelectedPermission(null);
        fetchPermissions();
      } else {
        message.error(result.error || '更新权限失败');
      }
    } catch (error) {
      message.error('网络错误');
    }
  };

  // 删除权限
  const handleDeletePermission = async (permissionId: string) => {
    try {
      const response = await fetch(`/api/admin/permissions/${permissionId}`, {
        method: 'DELETE',
      });

      const result = await response.json();
      if (result.success) {
        message.success('权限删除成功');
        fetchPermissions();
      } else {
        message.error(result.error || '删除权限失败');
      }
    } catch (error) {
      message.error('网络错误');
    }
  };

  // 获取分类图标
  const getCategoryIcon = (category: string) => {
    const iconMap: Record<string, React.ReactNode> = {
      user_management: <SafetyOutlined />,
      content_management: <FileOutlined />,
      system_settings: <SettingOutlined />,
      ai_features: <ApiOutlined />,
      data_analytics: <DatabaseOutlined />,
      other: <FolderOutlined />
    };
    return iconMap[category] || <FolderOutlined />;
  };

  // 获取资源类型图标
  const getResourceTypeIcon = (resourceType: string) => {
    const iconMap: Record<string, React.ReactNode> = {
      api: <ApiOutlined />,
      route: <GlobalOutlined />,
      table: <DatabaseOutlined />,
      file: <FileOutlined />,
      feature: <SettingOutlined />,
      other: <FolderOutlined />
    };
    return iconMap[resourceType] || <FolderOutlined />;
  };

  // 获取操作颜色
  const getActionColor = (action: string) => {
    const colorMap: Record<string, string> = {
      read: 'blue',
      create: 'green',
      update: 'orange',
      delete: 'red',
      execute: 'purple',
      manage: 'gold'
    };
    return colorMap[action] || 'default';
  };

  // 生成权限树数据
  const generateTreeData = (): DataNode[] => {
    const categoryMap: Record<string, Permission[]> = {};
    
    permissions.forEach(permission => {
      if (!categoryMap[permission.category]) {
        categoryMap[permission.category] = [];
      }
      categoryMap[permission.category].push(permission);
    });

    return Object.entries(categoryMap).map(([category, perms]) => ({
      title: (
        <Space>
          {getCategoryIcon(category)}
          <span>{categoryOptions.find(opt => opt.value === category)?.label || category}</span>
          <Badge count={perms.length} style={{ backgroundColor: '#52c41a' }} />
        </Space>
      ),
      key: category,
      children: perms.map(perm => ({
        title: (
          <Space>
            {getResourceTypeIcon(perm.resource_type)}
            <span>{perm.display_name}</span>
            <Tag color={getActionColor(perm.action)}>{perm.action}</Tag>
            {!perm.is_active && <Badge status="default" />}
          </Space>
        ),
        key: perm.id,
        isLeaf: true
      }))
    }));
  };

  // 表格列定义
  const columns: ColumnsType<Permission> = [
    {
      title: '权限名称',
      key: 'permission',
      width: 250,
      render: (_, record) => (
        <Space>
          {getCategoryIcon(record.category)}
          <div>
            <div className={styles.permissionName}>{record.display_name}</div>
            <div className={styles.permissionCode}>{record.name}</div>
          </div>
        </Space>
      ),
    },
    {
      title: '描述',
      dataIndex: 'description',
      key: 'description',
      ellipsis: true,
      render: (text) => text || '-',
    },
    {
      title: '分类',
      dataIndex: 'category',
      key: 'category',
      width: 120,
      render: (category) => (
        <Tag color="blue">
          {categoryOptions.find(opt => opt.value === category)?.label || category}
        </Tag>
      ),
    },
    {
      title: '资源类型',
      dataIndex: 'resource_type',
      key: 'resource_type',
      width: 120,
      render: (resourceType) => (
        <Space>
          {getResourceTypeIcon(resourceType)}
          <span>{resourceTypeOptions.find(opt => opt.value === resourceType)?.label || resourceType}</span>
        </Space>
      ),
    },
    {
      title: '操作',
      dataIndex: 'action',
      key: 'action',
      width: 100,
      render: (action) => (
        <Tag color={getActionColor(action)}>
          {actionOptions.find(opt => opt.value === action)?.label || action}
        </Tag>
      ),
    },
    {
      title: '类型',
      dataIndex: 'is_system',
      key: 'is_system',
      width: 100,
      render: (isSystem) => (
        <Tag color={isSystem ? 'blue' : 'green'}>
          {isSystem ? '系统权限' : '自定义'}
        </Tag>
      ),
    },
    {
      title: '状态',
      dataIndex: 'is_active',
      key: 'is_active',
      width: 100,
      render: (isActive) => (
        <Badge 
          status={isActive ? 'success' : 'default'} 
          text={isActive ? '启用' : '禁用'} 
        />
      ),
    },
    {
      title: '角色数',
      dataIndex: 'role_count',
      key: 'role_count',
      width: 100,
      render: (count) => count || 0,
    },
    {
      title: '用户数',
      dataIndex: 'user_count',
      key: 'user_count',
      width: 100,
      render: (count) => count || 0,
    },
    {
      title: '创建时间',
      dataIndex: 'created_at',
      key: 'created_at',
      width: 150,
      render: (date) => new Date(date).toLocaleString(),
      sorter: true,
    },
    {
      title: '操作',
      key: 'actions',
      width: 150,
      fixed: 'right',
      render: (_, record) => (
        <Space size="small">
          <Tooltip title="查看详情">
            <Button
              type="text"
              size="small"
              icon={<EyeOutlined />}
              onClick={() => {
                setSelectedPermission(record);
                editForm.setFieldsValue(record);
                setEditModalVisible(true);
              }}
            />
          </Tooltip>
          <Tooltip title="编辑">
            <Button
              type="text"
              size="small"
              icon={<EditOutlined />}
              disabled={record.is_system}
              onClick={() => {
                setSelectedPermission(record);
                editForm.setFieldsValue(record);
                setEditModalVisible(true);
              }}
            />
          </Tooltip>
          <Popconfirm
            title="确定要删除这个权限吗？"
            description="删除后将无法恢复，请谨慎操作。"
            onConfirm={() => handleDeletePermission(record.id)}
            okText="确定"
            cancelText="取消"
            disabled={record.is_system}
          >
            <Tooltip title={record.is_system ? '系统权限不能删除' : '删除'}>
              <Button
                type="text"
                size="small"
                danger
                disabled={record.is_system}
                icon={<DeleteOutlined />}
              />
            </Tooltip>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  useEffect(() => {
    fetchPermissions();
  }, [currentPage, pageSize, searchText, categoryFilter, resourceTypeFilter, isSystemFilter, isActiveFilter]);

  return (
    <AdminLayout pageTitle="权限管理">
      <div className={styles.permissionsPage}>
        {/* 统计卡片 */}
        {stats && (
          <Row gutter={16} className={styles.statsRow}>
            <Col span={6}>
              <Card>
                <Statistic
                  title="总权限数"
                  value={stats.total}
                  prefix={<KeyOutlined />}
                />
              </Card>
            </Col>
            <Col span={6}>
              <Card>
                <Statistic
                  title="启用权限"
                  value={stats.active}
                  valueStyle={{ color: '#3f8600' }}
                />
              </Card>
            </Col>
            <Col span={6}>
              <Card>
                <Statistic
                  title="系统权限"
                  value={stats.system}
                  valueStyle={{ color: '#1890ff' }}
                />
              </Card>
            </Col>
            <Col span={6}>
              <Card>
                <Statistic
                  title="自定义权限"
                  value={stats.custom}
                  prefix={<SettingOutlined />}
                />
              </Card>
            </Col>
          </Row>
        )}

        {/* 搜索和筛选 */}
        <Card className={styles.filterCard}>
          <Row gutter={16} align="middle">
            <Col flex="auto">
              <Space size="middle" wrap>
                <Search
                  placeholder="搜索权限名称、描述"
                  allowClear
                  style={{ width: 300 }}
                  onSearch={setSearchText}
                  enterButton={<SearchOutlined />}
                />
                <Select
                  placeholder="分类筛选"
                  allowClear
                  style={{ width: 120 }}
                  value={categoryFilter}
                  onChange={setCategoryFilter}
                >
                  {categoryOptions.map(option => (
                    <Option key={option.value} value={option.value}>
                      {option.label}
                    </Option>
                  ))}
                </Select>
                <Select
                  placeholder="资源类型"
                  allowClear
                  style={{ width: 120 }}
                  value={resourceTypeFilter}
                  onChange={setResourceTypeFilter}
                >
                  {resourceTypeOptions.map(option => (
                    <Option key={option.value} value={option.value}>
                      {option.label}
                    </Option>
                  ))}
                </Select>
                <Select
                  placeholder="类型筛选"
                  allowClear
                  style={{ width: 120 }}
                  value={isSystemFilter}
                  onChange={setIsSystemFilter}
                >
                  <Option value="true">系统权限</Option>
                  <Option value="false">自定义</Option>
                </Select>
                <Select
                  placeholder="状态筛选"
                  allowClear
                  style={{ width: 120 }}
                  value={isActiveFilter}
                  onChange={setIsActiveFilter}
                >
                  <Option value="true">启用</Option>
                  <Option value="false">禁用</Option>
                </Select>
              </Space>
            </Col>
            <Col>
              <Space>
                <Button
                  icon={<FolderOutlined />}
                  onClick={() => setTreeModalVisible(true)}
                >
                  树形视图
                </Button>
                <Button
                  icon={<ReloadOutlined />}
                  onClick={fetchPermissions}
                  loading={loading}
                >
                  刷新
                </Button>
                <Button
                  type="primary"
                  icon={<PlusOutlined />}
                  onClick={() => setCreateModalVisible(true)}
                >
                  新增权限
                </Button>
              </Space>
            </Col>
          </Row>
        </Card>

        {/* 权限表格 */}
        <Card>
          <Table<Permission>
            columns={columns}
            dataSource={permissions}
            rowKey="id"
            loading={loading}
            scroll={{ x: 'max-content' }}
            pagination={{
              current: currentPage,
              pageSize: pageSize,
              total: total,
              showSizeChanger: true,
              showQuickJumper: true,
              showTotal: (total, range) => `第 ${range[0]}-${range[1]} 条，共 ${total} 条`,
              onChange: (page, size) => {
                setCurrentPage(page);
                setPageSize(size || 20);
              },
            }}
          />
        </Card>

        {/* 创建权限弹窗 */}
        <Modal
          title={<><PlusOutlined /> 新增权限</>}
          open={createModalVisible}
          onCancel={() => {
            setCreateModalVisible(false);
            createForm.resetFields();
          }}
          footer={null}
          width={700}
        >
          <Form
            form={createForm}
            layout="vertical"
            onFinish={handleCreatePermission}
          >
            <Row gutter={16}>
              <Col span={12}>
                <Form.Item
                  name="name"
                  label="权限标识"
                  rules={[
                    { required: true, message: '请输入权限标识' },
                    { pattern: /^[a-zA-Z0-9_:]+$/, message: '只能包含字母、数字、下划线和冒号' }
                  ]}
                >
                  <Input placeholder="如：user:create, content:read" />
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item
                  name="display_name"
                  label="显示名称"
                  rules={[{ required: true, message: '请输入显示名称' }]}
                >
                  <Input placeholder="如：创建用户, 查看内容" />
                </Form.Item>
              </Col>
            </Row>
            <Form.Item
              name="description"
              label="权限描述"
            >
              <TextArea rows={3} placeholder="请输入权限描述" />
            </Form.Item>
            <Row gutter={16}>
              <Col span={8}>
                <Form.Item
                  name="category"
                  label="权限分类"
                  rules={[{ required: true, message: '请选择权限分类' }]}
                >
                  <Select placeholder="请选择分类">
                    {categoryOptions.map(option => (
                      <Option key={option.value} value={option.value}>
                        {option.label}
                      </Option>
                    ))}
                  </Select>
                </Form.Item>
              </Col>
              <Col span={8}>
                <Form.Item
                  name="resource_type"
                  label="资源类型"
                  rules={[{ required: true, message: '请选择资源类型' }]}
                >
                  <Select placeholder="请选择资源类型">
                    {resourceTypeOptions.map(option => (
                      <Option key={option.value} value={option.value}>
                        {option.label}
                      </Option>
                    ))}
                  </Select>
                </Form.Item>
              </Col>
              <Col span={8}>
                <Form.Item
                  name="action"
                  label="操作类型"
                  rules={[{ required: true, message: '请选择操作类型' }]}
                >
                  <Select placeholder="请选择操作">
                    {actionOptions.map(option => (
                      <Option key={option.value} value={option.value}>
                        {option.label}
                      </Option>
                    ))}
                  </Select>
                </Form.Item>
              </Col>
            </Row>
            <Form.Item
              name="resource_id"
              label="资源ID"
            >
              <Input placeholder="可选，特定资源的ID" />
            </Form.Item>
            <Form.Item
              name="is_active"
              label="启用状态"
              valuePropName="checked"
              initialValue={true}
            >
              <Switch checkedChildren="启用" unCheckedChildren="禁用" />
            </Form.Item>
            <Form.Item>
              <Space style={{ width: '100%', justifyContent: 'flex-end' }}>
                <Button onClick={() => {
                  setCreateModalVisible(false);
                  createForm.resetFields();
                }}>
                  取消
                </Button>
                <Button type="primary" htmlType="submit">
                  创建
                </Button>
              </Space>
            </Form.Item>
          </Form>
        </Modal>

        {/* 编辑权限弹窗 */}
        <Modal
          title={<><EditOutlined /> 编辑权限</>}
          open={editModalVisible}
          onCancel={() => {
            setEditModalVisible(false);
            editForm.resetFields();
            setSelectedPermission(null);
          }}
          footer={null}
          width={700}
        >
          <Form
            form={editForm}
            layout="vertical"
            onFinish={handleUpdatePermission}
          >
            <Row gutter={16}>
              <Col span={12}>
                <Form.Item
                  name="name"
                  label="权限标识"
                  rules={[
                    { required: true, message: '请输入权限标识' },
                    { pattern: /^[a-zA-Z0-9_:]+$/, message: '只能包含字母、数字、下划线和冒号' }
                  ]}
                >
                  <Input placeholder="如：user:create, content:read" disabled={selectedPermission?.is_system} />
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item
                  name="display_name"
                  label="显示名称"
                  rules={[{ required: true, message: '请输入显示名称' }]}
                >
                  <Input placeholder="如：创建用户, 查看内容" />
                </Form.Item>
              </Col>
            </Row>
            <Form.Item
              name="description"
              label="权限描述"
            >
              <TextArea rows={3} placeholder="请输入权限描述" />
            </Form.Item>
            <Row gutter={16}>
              <Col span={8}>
                <Form.Item
                  name="category"
                  label="权限分类"
                  rules={[{ required: true, message: '请选择权限分类' }]}
                >
                  <Select placeholder="请选择分类" disabled={selectedPermission?.is_system}>
                    {categoryOptions.map(option => (
                      <Option key={option.value} value={option.value}>
                        {option.label}
                      </Option>
                    ))}
                  </Select>
                </Form.Item>
              </Col>
              <Col span={8}>
                <Form.Item
                  name="resource_type"
                  label="资源类型"
                  rules={[{ required: true, message: '请选择资源类型' }]}
                >
                  <Select placeholder="请选择资源类型" disabled={selectedPermission?.is_system}>
                    {resourceTypeOptions.map(option => (
                      <Option key={option.value} value={option.value}>
                        {option.label}
                      </Option>
                    ))}
                  </Select>
                </Form.Item>
              </Col>
              <Col span={8}>
                <Form.Item
                  name="action"
                  label="操作类型"
                  rules={[{ required: true, message: '请选择操作类型' }]}
                >
                  <Select placeholder="请选择操作" disabled={selectedPermission?.is_system}>
                    {actionOptions.map(option => (
                      <Option key={option.value} value={option.value}>
                        {option.label}
                      </Option>
                    ))}
                  </Select>
                </Form.Item>
              </Col>
            </Row>
            <Form.Item
              name="resource_id"
              label="资源ID"
            >
              <Input placeholder="可选，特定资源的ID" disabled={selectedPermission?.is_system} />
            </Form.Item>
            <Form.Item
              name="is_active"
              label="启用状态"
              valuePropName="checked"
            >
              <Switch checkedChildren="启用" unCheckedChildren="禁用" />
            </Form.Item>
            {selectedPermission?.is_system && (
              <div style={{ marginBottom: 16, padding: 12, background: '#fff7e6', border: '1px solid #ffd591', borderRadius: 4 }}>
                <Space>
                  <SafetyOutlined style={{ color: '#fa8c16' }} />
                  <span style={{ color: '#fa8c16' }}>系统权限的核心属性不能修改</span>
                </Space>
              </div>
            )}
            <Form.Item>
              <Space style={{ width: '100%', justifyContent: 'flex-end' }}>
                <Button onClick={() => {
                  setEditModalVisible(false);
                  editForm.resetFields();
                  setSelectedPermission(null);
                }}>
                  取消
                </Button>
                <Button type="primary" htmlType="submit">
                  保存
                </Button>
              </Space>
            </Form.Item>
          </Form>
        </Modal>

        {/* 权限树形视图弹窗 */}
        <Modal
          title={<><FolderOutlined /> 权限树形视图</>}
          open={treeModalVisible}
          onCancel={() => setTreeModalVisible(false)}
          width={800}
          footer={[
            <Button key="close" onClick={() => setTreeModalVisible(false)}>
              关闭
            </Button>
          ]}
        >
          <div className={styles.treeContainer}>
            <Tree
              treeData={generateTreeData()}
              defaultExpandAll
              showIcon
              blockNode
            />
          </div>
        </Modal>
      </div>
    </AdminLayout>
  );
};

export default PermissionsPage;